<template>
  <div class="creation-center-bg">
    <div class="creation-center">
      <div class="center-header">
        <h1>创作中心</h1>
        <p>管理您的内容创作流程，从热搜主题爬取到AI分析</p>
      </div>
      
      <!-- 1. 热搜主题爬取 -->
      <div class="feature-card" :class="{'active-card': crawlerRunning}">
        <div class="feature-header">
          <div class="feature-index">1</div>
          <el-icon><Promotion /></el-icon>
          <span>爬取热搜主题</span>
        </div>
        <div class="feature-description">爬取热门搜索主题，获取最新的热点话题</div>
        <div class="feature-actions feature-actions-row">
          <div class="feature-actions-group" style="width: 100%">
            <div class="time-picker-group">
              <el-time-picker
                v-model="crawlerConfig.scheduleTimeObj"
                format="HH:mm"
                placeholder="定时执行时间"
                @change="handleTimeChange"
                class="custom-time-picker"
              />
              <el-button type="primary" @click="submitConfigForm" :loading="configLoading" size="small" class="time-set-btn">设置时间</el-button>
            </div>
            <div class="feature-actions-subrow">
              <el-button type="primary" @click="handleCrawlNow" :loading="crawlerLoading" :disabled="crawlerRunning" size="large" class="action-btn">
                <el-icon><Promotion /></el-icon>
                <span>立即爬取</span>
              </el-button>
              <el-button type="success" @click="handleStartCrawlerScheduled" :loading="crawlerLoading" :disabled="crawlerRunning" size="large" class="action-btn">
                <el-icon><Clock /></el-icon>
                <span>定时爬取</span>
              </el-button>
            </div>
            <div class="feature-actions-subrow">
              <el-button type="danger" @click="handleStopCrawler" :loading="stopCrawlerLoading" :disabled="!crawlerRunning" size="large" class="action-btn">
                <el-icon><Close /></el-icon>
                <span>停止爬取</span>
              </el-button>
              <el-button type="info" @click="goToTopicPage" size="large" class="action-btn">
                <el-icon><Link /></el-icon>
                <span>主题管理</span>
              </el-button>
            </div>
          </div>
        </div>
        <div class="feature-status">
          <el-tag v-if="crawlerRunning" type="success" class="status-tag">爬虫运行中</el-tag>
          <el-tag v-else type="info" class="status-tag">爬虫已停止</el-tag>
        </div>
      </div>
      
      <!-- 2. 相关链接采集 -->
      <div class="feature-card" :class="{'active-card': relatedLinksCrawlerRunning}">
        <div class="feature-header">
          <div class="feature-index">2</div>
          <el-icon><Link /></el-icon>
          <span>相关链接采集</span>
        </div>
        <div class="feature-description">采集与主题相关的文章链接，丰富内容来源</div>
        <div class="feature-actions">
          <el-button type="primary" @click="handleStartRelatedLinksCrawler" :disabled="relatedLinksCrawlerRunning" class="action-btn">
            <el-icon><Promotion /></el-icon>
            <span>文章爬取</span>
          </el-button>
          <el-button type="info" @click="goToRelatedLinksPage" class="action-btn">
            <el-icon><Link /></el-icon>
            <span>链接管理</span>
          </el-button>
        </div>
        <div class="feature-status">
          <el-tag v-if="relatedLinksCrawlerRunning" type="success" class="status-tag">爬虫运行中</el-tag>
          <el-tag v-else type="info" class="status-tag">爬虫已停止</el-tag>
        </div>
      </div>
      
      <!-- 3. AI配置 -->
      <div class="feature-card">
        <div class="feature-header">
          <div class="feature-index">3</div>
          <el-icon><Setting /></el-icon>
          <span>AI配置</span>
        </div>
        <div class="feature-description">配置AI参数，优化分析效果和结果输出</div>
        <div class="feature-actions">
          <el-button type="primary" @click="goToAiConfigPage" class="action-btn">
            <el-icon><Setting /></el-icon>
            <span>AI配置管理</span>
          </el-button>
          <el-button type="success" @click="handleUploadWord" class="action-btn">
            <el-icon><Upload /></el-icon>
            <span>上传Word文档</span>
          </el-button>
        </div>
      </div>
      
      <!-- 4.AI分析 -->
      <div class="feature-card" :class="{'active-card': digestAnalyzing}">
        <div class="feature-header">
          <div class="feature-index">4</div>
          <el-icon><MagicStick /></el-icon>
          <span>AI分析</span>
        </div>
        <div class="feature-description">使用AI自动分析内容，生成摘要和关键信息</div>
        <div class="feature-actions">
          <el-button type="warning" @click="handleDigestAutoAnalyze" :loading="digestAnalyzing && !digestIsMinimized" :disabled="digestAnalyzing && !digestIsMinimized" class="action-btn">
            <el-icon><MagicStick /></el-icon>
            <span>{{ getDigestAnalyzeButtonText() }}</span>
          </el-button>
          <el-button type="info" @click="goToDigestPage" class="action-btn">
            <el-icon><Link /></el-icon>
            <span>AI生成文章管理</span>
          </el-button>
        </div>
        <div class="feature-status">
          <el-tag v-if="digestAnalyzing" type="success" class="status-tag">分析进行中</el-tag>
          <el-tag v-else type="info" class="status-tag">分析已停止</el-tag>
        </div>
      </div>

      <!-- 对话框保持不变 -->
      <el-dialog 
        title="爬虫进度" 
        v-model="relatedLinksCrawlerProgressVisible" 
        width="500px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="handleRelatedLinksProgressDialogClose"
        class="custom-dialog"
      >
        <!-- 对话框内容保持不变 -->
        <div class="progress-container">
          <el-progress :percentage="relatedLinksOverallPercentage" :status="relatedLinksProgressStatus" :stroke-width="10" />
          <div class="progress-text">已处理: {{ relatedLinksCrawler.processed }} / {{ relatedLinksCrawler.total || 0 }}</div>
          <div class="progress-actions">
            <el-button type="danger" @click="handleStopRelatedLinksCrawler" :disabled="!relatedLinksCrawlerRunning" :loading="relatedLinksStopCrawlerLoading">{{ relatedLinksStopCrawlerLoading ? '正在停止...' : '停止爬虫' }}</el-button>
            <el-button type="info" @click="refreshRelatedLinksProgress" :disabled="relatedLinksRefreshing">{{ relatedLinksRefreshing ? '刷新中...' : '手动刷新' }}</el-button>
          </div>
          <el-tag v-if="relatedLinksCrawler.error" type="danger" style="margin-top:10px;">{{ relatedLinksCrawler.error }}</el-tag>
        </div>
      </el-dialog>

      <!-- Word文档上传对话框 -->
      <el-dialog
        title="上传Word文档"
        v-model="uploadDialogVisible"
        width="600px"
        append-to-body
        destroy-on-close
        class="custom-dialog"
      >
        <el-form ref="uploadFormRef" :model="uploadForm" :rules="uploadRules" label-width="100px">
          <el-form-item label="热搜主题ID" prop="topicId">
            <el-input v-model="uploadForm.topicId" placeholder="请输入热搜主题ID" />
          </el-form-item>
          <el-form-item label="Word文档" prop="file">
            <el-upload
              ref="uploadRef"
              :limit="1"
              accept=".doc,.docx"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              drag
            >
              <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传 .doc/.docx 文件，且不超过 10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="来源URL" prop="sourceUrl">
            <el-input v-model="uploadForm.sourceUrl" placeholder="请输入来源URL（可选）" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="uploadDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确 定</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { listTopic, getCrawlerConfig, updateCrawlerConfig, startCrawler, stopCrawler, getCrawlerStatus } from '@/api/topic/topic'
import { startCrawler as startRelatedLinksCrawler, stopCrawler as stopRelatedLinksCrawler, getCrawlerProgress as getRelatedLinksCrawlerProgress } from '@/api/related_links/related_links'
import { autoAnalyzeAllTopics as digestAutoAnalyzeAllTopics, getAnalysisProgress as getDigestAnalysisProgress, stopAnalysisTask as stopDigestAnalysisTask } from '@/api/digest/digest'
import { uploadWordDocument, getNextTopicId } from '@/api/article/article'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Minus, Close, Promotion, Link, Setting, MagicStick, Clock, Upload, UploadFilled } from '@element-plus/icons-vue'

const router = useRouter()

// 主题列表
const topicList = ref([])
const topicLoading = ref(false)

// 爬虫配置
const crawlerConfig = reactive({
  scheduleTime: '',
  scheduleTimeObj: null
})
const configLoading = ref(false)
const crawlerLoading = ref(false)
const stopCrawlerLoading = ref(false)
const crawlerRunning = ref(false)

// 相关链接采集爬虫相关变量
const relatedLinksCrawler = ref({
  total: 0,
  totalBatches: 0,
  currentBatch: 0,
  processed: 0,
  success: 0,
  failure: 0,
  status: 0,
  error: null
})
const relatedLinksCrawlerProgressVisible = ref(false)
const relatedLinksCrawlerRunning = ref(false)
const relatedLinksStopCrawlerLoading = ref(false)
const relatedLinksRefreshing = ref(false)
const relatedLinksCurrentTime = ref('')
let relatedLinksProgressTimer = null

const relatedLinksStatusConfig = {
  0: { type: 'info', label: '已停止' },
  1: { type: 'primary', label: '运行中' },
  2: { type: 'success', label: '已完成' },
  3: { type: 'info', label: '已停止' },
  4: { type: 'danger', label: '执行错误' }
}

const relatedLinksOverallPercentage = computed(() => {
  if (!relatedLinksCrawler.value.total || relatedLinksCrawler.value.total <= 0) return 0;
  return Math.round((relatedLinksCrawler.value.processed / relatedLinksCrawler.value.total) * 100);
})
const relatedLinksProgressStatus = computed(() => {
  if (relatedLinksCrawler.value.status === 2) return 'success';
  if (relatedLinksCrawler.value.status === 4) return 'exception';
  return '';
})
const relatedLinksSuccessRate = computed(() => {
  if (!relatedLinksCrawler.value.processed || relatedLinksCrawler.value.processed <= 0) return '0.00';
  return ((relatedLinksCrawler.value.success / relatedLinksCrawler.value.processed) * 100).toFixed(2);
})

function getTopicList() {
  topicLoading.value = true
  listTopic({ pageNum: 1, pageSize: 10, orderByColumn: 'createdTime', isAsc: 'desc' })
    .then(res => {
      topicList.value = res.rows || []
      topicLoading.value = false
    })
    .catch(() => { topicLoading.value = false })
}

function getCrawlerConfigInfo() {
  getCrawlerConfig().then(res => {
    if (res.code === 200 && res.data) {
      const timeStr = res.data.replace(/\[|\]|'|"/g, '').trim()
      crawlerConfig.scheduleTime = timeStr
      if (timeStr) {
        const [hours, minutes] = timeStr.split(':')
        const date = new Date()
        date.setHours(parseInt(hours))
        date.setMinutes(parseInt(minutes))
        crawlerConfig.scheduleTimeObj = date
      }
    }
  })
}

function handleTimeChange(time) {
  if (time) {
    const hours = time.getHours().toString().padStart(2, '0')
    const minutes = time.getMinutes().toString().padStart(2, '0')
    crawlerConfig.scheduleTime = `${hours}:${minutes}`
  } else {
    crawlerConfig.scheduleTime = ''
  }
}
function submitConfigForm() {
  if (!crawlerConfig.scheduleTime) {
    ElMessage.error('请选择定时执行时间')
    return
  }
  configLoading.value = true
  updateCrawlerConfig({ scheduleTime: crawlerConfig.scheduleTime }).then(res => {
    ElMessage.success('爬虫定时配置已更新')
    configLoading.value = false
    getCrawlerConfigInfo()
  }).catch(() => { configLoading.value = false })
}

function getCrawlerStatusInfo() {
  getCrawlerStatus().then(res => {
    crawlerRunning.value = !!res.data
  })
}

function handleCrawlNow() {
  crawlerLoading.value = true
  startCrawler(true).then(() => {
    ElMessage.success('爬虫已启动，正在立即执行爬取任务！')
    crawlerLoading.value = false
    setTimeout(() => {
      getTopicList()
      getCrawlerStatusInfo()
    }, 3000)
  }).catch(() => { crawlerLoading.value = false })
}

function handleStartCrawlerScheduled() {
  crawlerLoading.value = true
  startCrawler(false).then(() => {
    ElMessage.success('爬虫已在后台启动，将按照预定时间执行爬取任务！')
    crawlerLoading.value = false
    crawlerRunning.value = true
    setTimeout(() => {
      getTopicList()
      getCrawlerStatusInfo()
    }, 2000)
  }).catch(() => { crawlerLoading.value = false })
}

function handleStopCrawler() {
  stopCrawlerLoading.value = true
  stopCrawler().then(() => {
    ElMessage.success('爬虫已停止！')
    stopCrawlerLoading.value = false
    crawlerRunning.value = false
  }).catch(() => { stopCrawlerLoading.value = false })
}

function goToTopicPage() {
  router.push({ path: '/article_manage/topic' })
}

function updateRelatedLinksCurrentTime() {
  relatedLinksCurrentTime.value = new Date().toLocaleTimeString();
}

function handleStartRelatedLinksCrawler() {
  // 重置爬虫数据
  relatedLinksCrawler.value = {
    total: 0,
    totalBatches: 0,
    currentBatch: 0,
    processed: 0,
    success: 0,
    failure: 0,
    status: 0,
    error: null
  }
  startRelatedLinksCrawler().then(response => {
    if (response.code === 200) {
      relatedLinksCrawlerRunning.value = true
      relatedLinksCrawlerProgressVisible.value = true
      if (response.data && typeof response.data === 'object') {
        Object.keys(response.data).forEach(key => {
          if (relatedLinksCrawler.value.hasOwnProperty(key)) {
            relatedLinksCrawler.value[key] = response.data[key]
          }
        })
      }
      startRelatedLinksProgressPolling()
      ElMessage.success('爬虫启动成功')
    } else {
      ElMessage.error(response.msg || '启动爬虫失败')
    }
  }).catch(error => {
    ElMessage.error(error.message || '启动爬虫失败')
    relatedLinksCrawlerRunning.value = false
  })
}

function handleStopRelatedLinksCrawler() {
  ElMessageBox.confirm('确认停止爬虫任务？', '提示', { type: 'warning' }).then(() => {
    relatedLinksStopCrawlerLoading.value = true
    stopRelatedLinksCrawler().then(response => {
      if (response.code === 200) {
        stopRelatedLinksProgressPolling()
        relatedLinksCrawlerRunning.value = false
        relatedLinksCrawler.value.status = 3
        ElMessage.success('爬虫已停止')
      } else {
        ElMessage.error(response.msg || '停止爬虫失败')
      }
    }).catch(error => {
      ElMessage.error(error.message || '停止爬虫失败')
    }).finally(() => {
      relatedLinksStopCrawlerLoading.value = false
    })
  })
}

function handleRelatedLinksProgressDialogClose() {
  if (relatedLinksCrawlerRunning.value) {
    ElMessageBox.confirm('爬虫正在运行中，确认关闭将停止爬虫任务？', '提示', { type: 'warning' }).then(() => {
      handleStopRelatedLinksCrawler()
    }).catch(() => {
      // 用户取消关闭，保持弹窗打开
      relatedLinksCrawlerProgressVisible.value = true
    })
  } else {
    stopRelatedLinksProgressPolling()
    relatedLinksCrawlerProgressVisible.value = false
  }
}

function refreshRelatedLinksProgress() {
  if (relatedLinksRefreshing.value) return
  relatedLinksRefreshing.value = true
  getRelatedLinksCrawlerProgress().then(response => {
    if (response.code === 200 && response.data) {
      updateRelatedLinksCrawlerProgress(response.data)
      ElMessage.success('进度已刷新')
    }
  }).catch(() => {
    ElMessage.error('刷新进度失败')
  }).finally(() => {
    relatedLinksRefreshing.value = false
  })
}

function updateRelatedLinksCrawlerProgress(data) {
  Object.keys(data).forEach(key => {
    if (relatedLinksCrawler.value.hasOwnProperty(key)) {
      if ([
        'total', 'totalBatches', 'currentBatch', 'processed', 'success', 'failure', 'status'
      ].includes(key)) {
        relatedLinksCrawler.value[key] = Number(data[key]) || 0
      } else {
        relatedLinksCrawler.value[key] = data[key]
      }
    }
  })
  updateRelatedLinksCurrentTime()
}

function startRelatedLinksProgressPolling() {
  if (relatedLinksProgressTimer) clearInterval(relatedLinksProgressTimer)
  fetchRelatedLinksProgress()
  relatedLinksProgressTimer = setInterval(() => {
    fetchRelatedLinksProgress()
  }, 1000)
}
function fetchRelatedLinksProgress() {
  getRelatedLinksCrawlerProgress().then(response => {
    if (response.code === 200 && response.data) {
      updateRelatedLinksCrawlerProgress(response.data)
      const status = Number(response.data.status)
      if ([2, 4].includes(status)) {
        stopRelatedLinksProgressPolling()
        relatedLinksCrawlerRunning.value = false
        const msg = status === 2 ? '爬虫任务已完成！' : '爬虫任务执行出错'
        const msgType = status === 2 ? 'success' : 'error'
        ElMessage[msgType](msg)
      } else if (status === 3) {
        stopRelatedLinksProgressPolling()
        relatedLinksCrawlerRunning.value = false
      }
    }
  }).catch(() => {
    if (!relatedLinksCrawler.value.errorCount) relatedLinksCrawler.value.errorCount = 0
    relatedLinksCrawler.value.errorCount++
    if (relatedLinksCrawler.value.errorCount > 5) {
      stopRelatedLinksProgressPolling()
      relatedLinksCrawlerRunning.value = false
      ElMessage.error('获取进度失败，请手动刷新')
    }
  })
}
function stopRelatedLinksProgressPolling() {
  if (relatedLinksProgressTimer) {
    clearInterval(relatedLinksProgressTimer)
    relatedLinksProgressTimer = null
  }
}
function goToRelatedLinksPage() {
  router.push({ path: '/article_manage/related_links' })
}

function goToAiConfigPage() {
  router.push({ path: '/ai_config_management' })
}

// digest AI自动分析相关变量
const digestAnalyzing = ref(false)
const digestIsMinimized = ref(false)
const digestCanStop = ref(true)
const digestProgressVisible = ref(false)
const digestAnalysisVisible = ref(false)
const digestAnalysisResult = ref({ success: false, message: '', data: null })
const digestProgressData = ref({
  percentage: 0,
  status: '',
  statusText: '准备中',
  totalCount: 0,
  processedCount: 0,
  successCount: 0,
  failureCount: 0,
  currentProcessing: '',
  taskId: ''
})
let digestProgressTimer = null

// Word文档上传相关变量
const uploadDialogVisible = ref(false)
const uploadLoading = ref(false)
const fileList = ref([])
const uploadForm = ref({
  topicId: '',
  sourceUrl: ''
})
const uploadRules = {
  topicId: [
    { required: true, message: "热搜主题ID不能为空", trigger: "blur" }
  ]
}

function handleUploadWord() {
  // 先获取下一个可用的topicId
  getNextTopicId().then(response => {
    if (response.code === 200) {
      uploadForm.value = {
        topicId: response.data.toString(),
        sourceUrl: ''
      }
    } else {
      ElMessage.error("获取topicId失败: " + response.msg)
      return
    }
  }).catch(error => {
    ElMessage.error("获取topicId失败: " + (error.message || "未知错误"))
    return
  })
  
  uploadDialogVisible.value = true
  fileList.value = []
}

function handleFileChange(file) {
  // 检查文件大小（10MB）
  const isLt10M = file.raw.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    fileList.value = []
    return
  }
  
  // 检查文件格式
  const isValidFormat = file.name.toLowerCase().endsWith('.doc') || file.name.toLowerCase().endsWith('.docx')
  if (!isValidFormat) {
    ElMessage.error('只能上传 .doc/.docx 格式的文件!')
    fileList.value = []
    return
  }
  
  fileList.value = [file]
}

function handleFileRemove() {
  fileList.value = []
}

function submitUpload() {
  if (fileList.value.length === 0) {
    ElMessage.error('请选择要上传的Word文档')
    return
  }
  
  uploadLoading.value = true
  
  const formData = new FormData()
  formData.append('file', fileList.value[0].raw)
  formData.append('topicId', uploadForm.value.topicId)
  if (uploadForm.value.sourceUrl) {
    formData.append('sourceUrl', uploadForm.value.sourceUrl)
  }
  
  uploadWordDocument(formData).then(response => {
    ElMessage.success("Word文档上传并解析成功")
    uploadDialogVisible.value = false
  }).catch(error => {
    ElMessage.error("上传失败: " + (error.message || "未知错误"))
  }).finally(() => {
    uploadLoading.value = false
  })
}

function handleDigestAutoAnalyze() {
  if (digestIsMinimized.value && digestAnalyzing.value && digestProgressData.value.taskId) {
    digestProgressVisible.value = true
    digestIsMinimized.value = false
    return
  }
  if (digestAnalyzing.value && digestProgressData.value.taskId) {
    digestProgressVisible.value = true
    return
  }
  ElMessageBox.confirm('确认对所有未处理的主题进行AI分析？', '提示', { type: 'warning' }).then(() => {
    digestAnalyzing.value = true
    digestProgressData.value = {
      percentage: 0,
      status: '',
      statusText: '准备中',
      totalCount: 0,
      processedCount: 0,
      successCount: 0,
      failureCount: 0,
      currentProcessing: '',
      taskId: ''
    }
    digestProgressVisible.value = true
    return digestAutoAnalyzeAllTopics()
  }).then(response => {
    if (response && response.code === 200 && response.data && response.data.taskId) {
      digestProgressData.value.taskId = response.data.taskId
      startDigestProgressPolling()
    } else {
      digestProgressVisible.value = false
      finishDigestAnalysis(response)
    }
  }).catch(error => {
    digestProgressVisible.value = false
    finishDigestAnalysis({
      code: 500,
      msg: error.message || '分析失败',
      data: null
    })
  })
}
function startDigestProgressPolling() {
  digestCanStop.value = true
  if (digestProgressTimer) clearInterval(digestProgressTimer)
  digestProgressTimer = setInterval(() => {
    if (!digestProgressData.value.taskId) {
      clearInterval(digestProgressTimer)
      return
    }
    getDigestAnalysisProgress(digestProgressData.value.taskId).then(response => {
      if (response.code === 200) {
        const data = response.data
        digestProgressData.value.totalCount = data.totalCount || 0
        digestProgressData.value.processedCount = data.processedCount || 0
        digestProgressData.value.successCount = data.successCount || 0
        digestProgressData.value.failureCount = data.failureCount || 0
        digestProgressData.value.currentProcessing = data.currentProcessing || ''
        digestProgressData.value.percentage = data.progressPercentage || 0
        if (data.status === 'COMPLETED') {
          digestProgressData.value.status = 'success'
          digestProgressData.value.statusText = '已完成'
          stopDigestProgressPolling()
          setTimeout(() => {
            digestProgressVisible.value = false
            finishDigestAnalysis({
              code: 200,
              msg: '分析完成！',
              data: {
                totalCount: data.totalCount,
                successCount: data.successCount,
                failCount: data.failureCount,
                duration: data.duration || 0
              }
            })
          }, 1000)
        } else if (data.status === 'ERROR') {
          digestProgressData.value.status = 'exception'
          digestProgressData.value.statusText = '错误'
          stopDigestProgressPolling()
          setTimeout(() => {
            digestProgressVisible.value = false
            finishDigestAnalysis({
              code: 500,
              msg: data.errorMessage || '分析出错',
              data: {
                totalCount: data.totalCount,
                successCount: data.successCount,
                failCount: data.failureCount,
                duration: data.duration || 0
              }
            })
          }, 1000)
        } else {
          digestProgressData.value.status = ''
          digestProgressData.value.statusText = '处理中'
        }
      } else {
        digestProgressData.value.status = 'exception'
        digestProgressData.value.statusText = '查询进度失败'
      }
    }).catch(() => {
      digestProgressData.value.status = 'exception'
      digestProgressData.value.statusText = '查询进度失败'
    })
  }, 1000)
}
function stopDigestProgressPolling() {
  if (digestProgressTimer) {
    clearInterval(digestProgressTimer)
    digestProgressTimer = null
  }
}
function finishDigestAnalysis(response) {
  digestAnalyzing.value = false
  digestCanStop.value = false
  digestIsMinimized.value = false
  digestAnalysisResult.value = {
    success: response.code === 200,
    message: response.code === 200 ? '分析完成！' : response.msg || '分析失败',
    data: response.data
  }
  digestAnalysisVisible.value = true
}
function handleDigestMinimize() {
  digestIsMinimized.value = true
  digestProgressVisible.value = false
  ElMessage.info('分析正在后台进行，可点击"AI自动分析"按钮查看进度')
}
function handleDigestStopAnalysis() {
  ElMessageBox.confirm('确定要停止当前分析任务吗？', '提示', { type: 'warning' }).then(() => {
    return stopDigestAnalysisTask(digestProgressData.value.taskId)
  }).then(() => {
    stopDigestProgressPolling()
    digestAnalyzing.value = false
    digestProgressVisible.value = false
    digestIsMinimized.value = false
    ElMessage.success('分析任务已停止')
  }).catch(error => {
    const errorMsg = error?.message || error?.msg || '停止任务失败'
    ElMessage.error('停止任务失败: ' + errorMsg)
  })
}
function getDigestAnalyzeButtonText() {
  if (digestIsMinimized.value) {
    return '查看进度'
  }
  return digestAnalyzing.value ? '分析中...' : 'AI自动分析'
}
function goToDigestPage() {
  router.push({ path: '/article_manage/digest' })
}

onMounted(() => {
  getTopicList()
  getCrawlerConfigInfo()
  getCrawlerStatusInfo()
})
</script>

<style scoped>
.creation-center-bg {
  background: linear-gradient(135deg, #f8faff 0%, #f0f5ff 100%);
  min-height: 100vh;
  padding: 40px 0;
}

.creation-center {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  justify-content: center;
}

.center-header {
  width: 100%;
  text-align: center;
  margin-bottom: 20px;
}

.center-header h1 {
  font-size: 32px;
  color: #1976d2;
  margin-bottom: 8px;
  font-weight: 600;
}

.center-header p {
  font-size: 16px;
  color: #606266;
  max-width: 600px;
  margin: 0 auto;
}

.feature-card {
  background: #fff;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
  padding: 32px 36px 28px 36px;
  flex: 1 1 420px;
  min-width: 340px;
  max-width: 560px;
  display: flex;
  flex-direction: column;
  gap: 18px;
  border: 1px solid #eaedf5;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.feature-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
  border-color: #d0e1fd;
}

.active-card {
  border-color: #409eff;
  box-shadow: 0 10px 30px rgba(64, 158, 255, 0.15);
}

.active-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #42a5f5, #1976d2);
}

.feature-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 20px;
  font-weight: 600;
  color: #1976d2;
  margin-bottom: 4px;
}

.feature-description {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  line-height: 1.5;
}

.feature-index {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #e3f0fc 0%, #c9e2f9 100%);
  color: #1976d2;
  font-weight: bold;
  font-size: 16px;
  border-radius: 50%;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.15);
}

.feature-actions {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  margin-bottom: 6px;
}

.feature-actions-row {
  justify-content: space-between;
  align-items: flex-start;
}

.feature-actions-group {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.feature-actions-right {
  margin-left: auto;
  gap: 12px;
}

.feature-actions-subrow {
  display: flex;
  gap: 16px;
  margin-top: 16px;
  width: 100%;
  justify-content: flex-start; /* 确保按钮左对齐 */
}

.time-picker-group {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f5f7fa;
  padding: 8px 12px;
  border-radius: 12px;
}

.custom-time-picker {
  width: 120px;
}

.time-set-btn {
  height: 32px;
  padding: 0 12px;
  border-radius: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  border-radius: 12px !important;
  font-size: 15px !important;
  font-weight: 500;
  padding: 0 24px !important;
  height: 42px !important;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.action-btn .el-icon {
  margin-right: 0 !important;
  font-size: 18px;
}

.el-button--primary {
  background: linear-gradient(90deg, #42a5f5 0%, #1976d2 100%);
  border: none;
}

.el-button--info {
  background: linear-gradient(90deg, #7ed6fb 0%, #409eff 100%);
  border: none;
}

.el-button--danger {
  background: linear-gradient(90deg, #ff7675 0%, #d32f2f 100%);
  border: none;
}

.el-button--success {
  background: linear-gradient(90deg, #81fbb8 0%, #28c76f 100%);
  border: none;
}

.el-button--warning {
  background: linear-gradient(90deg, #ffd166 0%, #f39c12 100%);
  border: none;
}

.feature-status {
  margin-top: 16px;
}

.status-tag {
  padding: 6px 12px;
  border-radius: 8px;
  font-size: 13px;
  font-weight: 500;
}

.progress-container {
  padding: 24px 0 8px 0;
}

.progress-text {
  margin-top: 12px;
  font-size: 14px;
  color: #606266;
  text-align: center;
}

.progress-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 16px;
}

.progress-info p {
  margin: 8px 0;
  font-size: 14px;
}

.custom-dialog .el-dialog__header {
  padding: 20px 24px;
  border-bottom: 1px solid #eaedf5;
}

.custom-dialog .el-dialog__body {
  padding: 24px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.dialog-header-buttons {
  display: flex;
  gap: 8px;
}

.dialog-header-buttons .el-button {
  padding: 6px;
  margin: 0;
}

/* Word文档上传对话框样式 */
.el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  text-align: center;
  margin-top: 8px;
}

.el-icon--upload {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

@media (max-width: 768px) {
  .creation-center {
    padding: 0 16px;
  }
  
  .feature-card {
    padding: 24px 20px;
  }
  
  .feature-actions-row {
    flex-direction: column;
  }
  
  .feature-actions-right {
    margin-left: 0;
    margin-top: 16px;
    width: 100%;
  }
  
  .action-btn {
    width: 100%;
  }
}
</style>